﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CPPEI.Coolzon.DesignServer.Domain.Services
{
    public class DataSourceService
    {
        public SingleResult<Entities.DataSource> CreateDataSource(Guid id,
            Guid solutionId,
            string name,
            string caption,
            string type,
            string version,
            string rtVersion,
            string address,
            string authenticationMode,
            string authenticationUser,
            string authenticationPassword,
            string creator)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.DataSource> rep = new Repositories.EntityRepository<Entities.DataSource>(dbContext);
                // check name is not exist
                if (rep.Get(p => p.Name == name) != null)
                {
                    return new SingleResult<Entities.DataSource>(false, 1, "name is exist", null);
                }

                Entities.DataSource entity = new Entities.DataSource();
                entity.Id = id;
                entity.Name = name;
                entity.Caption = caption;
                entity.Address = address;
                entity.CreatedTime = DateTime.Now;
                entity.Creator = creator;
                entity.RTVersion = rtVersion;
                entity.Version = version;
                entity.Type = type;
                entity.SolutionId = solutionId;
                entity.AuthenticationMode = authenticationMode;
                entity.AuthenticationPassword = authenticationPassword;
                entity.AuthenticationUser = authenticationUser;
                entity.Creator = creator;
                entity.CreatedTime = DateTime.Now;

                rep.Create(entity);

                if (dbContext.SaveChanges() > 0)
                {

                    //CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间成功,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                    return new SingleResult<Entities.DataSource>(true, 0, string.Empty, entity);
                }
                // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间失败,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                return new SingleResult<Entities.DataSource>(false, 1, string.Empty, null);
            }
        }
        public ServiceResult UpdateDataSource(Guid id,
            Guid solutionId,
            string name,
            string caption,
            string type,
            string version,
            string rtVersion,
            string address,
            string authenticationMode,
            string authenticationUser,
            string authenticationPassword,
            string creator)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.DataSource> rep = new Repositories.EntityRepository<Entities.DataSource>(dbContext);

                // check name is not exist
                if (rep.Get(p => p.Name == name && p.Id != id) != null)
                {
                    return new ServiceResult(false, 1, "name is exist");
                }

                Entities.DataSource entity = rep.Get(p => p.Id == id);
                if (entity == null)
                {
                    CPPEI.Coolzon.Common.Logger.ErrorToTag("DesignServer.Domain", string.Format("更新数据源失败，未发现数据源(DataSource)实体:{0}", entity.Id));
                    return new ServiceResult(false, 1, string.Empty);
                }
                entity.Name = name;
                entity.Caption = caption;
                entity.Address = address;
                entity.CreatedTime = DateTime.Now;
                entity.Creator = creator;
                entity.RTVersion = rtVersion;
                entity.Version = version;
                entity.Type = type;
                entity.SolutionId = solutionId;
                entity.AuthenticationMode = authenticationMode;
                entity.AuthenticationPassword = authenticationPassword;
                entity.AuthenticationUser = authenticationUser;
                entity.CreatedTime = DateTime.Now;
                entity.Creator = creator;

                rep.Update(entity);

                if (dbContext.SaveChanges() > 0)
                {

                    //CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间成功,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                    return new ServiceResult(true, 0, string.Empty);
                }
                // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间失败,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                return new ServiceResult(false, 1, string.Empty);
            }
        }

        public ServiceResult CreateDataSet(Models.DataSet dataSet)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.EntDataSet> rep = new Repositories.EntityRepository<Entities.EntDataSet>(dbContext);

                Entities.EntDataSet entity = new Entities.EntDataSet();
                entity.Id = dataSet.Id;
                entity.DataSourceId = dataSet.DataSourceId;
                entity.Name = dataSet.Name;
                entity.Caption = dataSet.Caption;
                entity.Type = dataSet.Type;
                entity.ValueString = dataSet.ValueString;
                entity.Creator = dataSet.Creator;
                entity.CreatedTime = dataSet.CreatedTime;
                entity.Creator = dataSet.Creator;

                rep.Create(entity);

                Repositories.EntityRepository<Entities.DataParameter> dpRep = new Repositories.EntityRepository<Entities.DataParameter>(dbContext);

                for (int index = 0; index < dataSet.Parameters.Count; index++)
                {
                    Entities.DataParameter parameter = new Entities.DataParameter();
                    parameter.Id = dataSet.Parameters[index].Id;
                    parameter.DataSetId = dataSet.Parameters[index].DataSetId;
                    parameter.Name = dataSet.Parameters[index].Name;
                    parameter.Caption = dataSet.Parameters[index].Caption;
                    parameter.ValueType = dataSet.Parameters[index].ValueType;
                    parameter.DataSourceId = dataSet.Parameters[index].DataSourceId;
                    parameter.Type = dataSet.Parameters[index].Type;

                    dpRep.Create(parameter);
                }
                int ret = dbContext.SaveChanges();
                if (ret > 0)
                {

                    //CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间成功,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                    return new ServiceResult(true, 0, string.Empty);
                }
                // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间失败,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                return new ServiceResult(false, 1, string.Empty);
            }
        }

        public ServiceResult UpdateDataSet(Models.DataSet dataSet)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.EntDataSet> rep = new Repositories.EntityRepository<Entities.EntDataSet>(dbContext);
                Entities.EntDataSet entity = rep.Get(p => p.Id == dataSet.Id);
                if (entity == null)
                {
                    CPPEI.Coolzon.Common.Logger.ErrorToTag("DesignServer.Domain", string.Format("更新数据源失败，未发现数据集(DataSet)实体:{0}", dataSet.Id));
                    return new ServiceResult(false, 1, string.Empty);
                }
                entity.DataSourceId = dataSet.DataSourceId;
                entity.Name = dataSet.Name;
                entity.Caption = dataSet.Caption;
                entity.Type = dataSet.Type;
                entity.ValueString = dataSet.ValueString;
                entity.Creator = dataSet.Creator;
                entity.CreatedTime = dataSet.CreatedTime;

                rep.Update(entity);

                dbContext.Database.ExecuteSqlCommand("delete from DataParameter where datasetid={0}", dataSet.Id);

                Repositories.EntityRepository<Entities.DataParameter> dpRep = new Repositories.EntityRepository<Entities.DataParameter>(dbContext);

                for (int index = 0; index < dataSet.Parameters.Count; index++)
                {
                    Entities.DataParameter parameter = new Entities.DataParameter();
                    parameter.Id = dataSet.Parameters[index].Id;
                    parameter.DataSetId = dataSet.Parameters[index].DataSetId;
                    parameter.Name = dataSet.Parameters[index].Name;
                    parameter.Caption = dataSet.Parameters[index].Caption;
                    parameter.ValueType = dataSet.Parameters[index].ValueType;
                    parameter.DataSourceId = dataSet.Parameters[index].DataSourceId;
                    parameter.Type = dataSet.Parameters[index].Type;

                    dpRep.Create(parameter);
                }

                if (dbContext.SaveChanges() > 0)
                {

                    //CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间成功,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                    return new ServiceResult(true, 0, string.Empty);
                }
                // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("用户{0}创建工作空间失败,(localPath:{1},computer:{2})", userIdentity, localPath, computer));
                return new ServiceResult(false, 1, string.Empty);
            }
        }

        public ListResult<Entities.DataSource> FindDataSourceList(string userIdentity, Guid solutionId)
        {
            if (solutionId == Guid.Empty)
            {
                using (DSDBContext dbContext = new DSDBContext())
                {
                    Repositories.EntityRepository<Entities.DataSource> rep = new Repositories.EntityRepository<Entities.DataSource>(dbContext);
                    List<Entities.DataSource> list = rep.GetList();
                    // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("获取用户:{0},computer:{}可用的工作空间成功.", userIdentity, computer));
                    return new ListResult<Entities.DataSource>(true, 0, string.Empty, list);
                }
            }
            else
            {
                using (DSDBContext dbContext = new DSDBContext())
                {
                    Repositories.EntityRepository<Entities.DataSource> rep = new Repositories.EntityRepository<Entities.DataSource>(dbContext);
                    List<Entities.DataSource> list = rep.GetList(p => p.SolutionId == solutionId);
                    // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("获取用户:{0},computer:{}可用的工作空间成功.", userIdentity, computer));
                    return new ListResult<Entities.DataSource>(true, 0, string.Empty, list);
                }
            }
        }

        public ListResult<Models.DataSet> FindDataSetList(string userIdentity, Guid dataSourceId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                List<Models.DataSet> models = new List<Models.DataSet>();

                Repositories.EntityRepository<Entities.EntDataSet> rep = new Repositories.EntityRepository<Entities.EntDataSet>(dbContext);

                Repositories.EntityRepository<Entities.DataParameter> dpRep = new Repositories.EntityRepository<Entities.DataParameter>(dbContext);

                List<Entities.EntDataSet> list = rep.GetList(p => p.DataSourceId == dataSourceId);
                for (int index = 0; index < list.Count; index++)
                {
                    Models.DataSet dataSet = new Models.DataSet();
                    dataSet.Id = list[index].Id;
                    dataSet.Name = list[index].Name;
                    dataSet.Caption = list[index].Caption;
                    dataSet.Type = list[index].Type;
                    dataSet.ValueString = list[index].ValueString;
                    dataSet.DataSourceId = list[index].DataSourceId;
                    dataSet.Parameters = dpRep.GetList(p => p.DataSetId == list[index].Id);
                    models.Add(dataSet);
                }
                // CPPEI.Coolzon.Common.Logger.InfoToTag("WorkspaceService", string.Format("获取用户:{0},computer:{}可用的工作空间成功.", userIdentity, computer));
                return new ListResult<Models.DataSet>(true, 0, string.Empty, models);
            }
        }

        public ServiceResult DeleteDataSource(Guid dataSourceId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                int res1 = dbContext.Database.ExecuteSqlCommand("delete from DataSource where id={0}", dataSourceId);
                int res2 = dbContext.Database.ExecuteSqlCommand("delete from DataSet where datasourceid={0}", dataSourceId);
                int res3 = dbContext.Database.ExecuteSqlCommand("delete from DataParameter where datasourceid={0}", dataSourceId);

                if (res1 + res2 + res3 > 0)
                {
                    return new ServiceResult(true, 0, string.Empty);
                }
            }
            return new ServiceResult(false, 1, string.Empty);
        }


        public ServiceResult DeleteDataSet(Guid dataSourceId, Guid dataSetId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                int ret = dbContext.Database.ExecuteSqlCommand("delete from DataSet where id={0} and datasourceid={1}", dataSetId, dataSourceId);
                dbContext.Database.ExecuteSqlCommand("delete from DataParameter where datasetid={0}", dataSetId);

                if (ret > 0)
                {
                    return new ServiceResult(true, 0, string.Empty);
                }
            }
            return new ServiceResult(false, 1, string.Empty);
        }

        public SingleResult<Models.PublishedDataSource> PubDataSource(Guid dataSourceId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.DataSource> dataSourceRep = new Repositories.EntityRepository<Entities.DataSource>(dbContext);
                Repositories.EntityRepository<Entities.EntDataSet> dataSetRep = new Repositories.EntityRepository<Entities.EntDataSet>(dbContext);
                Repositories.EntityRepository<Entities.DataParameter> dpRep = new Repositories.EntityRepository<Entities.DataParameter>(dbContext);

                Repositories.EntityRepository<Entities.EntPubDataSource> pubDataSourceRep = new Repositories.EntityRepository<Entities.EntPubDataSource>(dbContext);
                Repositories.EntityRepository<Entities.EntPubDataSet> pubDataSetRep = new Repositories.EntityRepository<Entities.EntPubDataSet>(dbContext);
                Repositories.EntityRepository<Entities.EntPubDataParameter> pubDPRep = new Repositories.EntityRepository<Entities.EntPubDataParameter>(dbContext);

                Entities.DataSource dataSource = dataSourceRep.Get(p => p.Id == dataSourceId);

                Models.PublishedDataSource modelDataSource = new Models.PublishedDataSource();

                if (dataSource == null)
                {
                    CPPEI.Coolzon.Common.Logger.ErrorToTag(Library.LogTAG, string.Format("发布数据源失败，未发现数据源:{0}", dataSourceId));
                    return new SingleResult<Models.PublishedDataSource>(false, 1, string.Empty, null);
                }

                // delete published history
                dbContext.Database.ExecuteSqlCommand("delete from PubDataSource where DataSourceId={0}", dataSourceId);
                dbContext.Database.ExecuteSqlCommand("delete from PubDataSet where DataSourceId={0}", dataSourceId);
                dbContext.Database.ExecuteSqlCommand("delete from PubDataParameter where DataSourceId={0}", dataSourceId);

                // update datasource
                dataSource.PublishedVersion = dataSource.Version;
                dataSource.PublishedTime = DateTime.Now;
                dataSourceRep.Update(dataSource);

                // insert pub datasource
                Entities.EntPubDataSource pubDataSource = new Entities.EntPubDataSource();
                pubDataSource.Id = Guid.NewGuid();
                pubDataSource.DataSourceId = dataSource.Id;
                pubDataSource.Name = dataSource.Name;
                pubDataSource.Caption = dataSource.Caption;
                pubDataSource.Address = dataSource.Address;
                pubDataSource.CreatedTime = dataSource.CreatedTime;
                pubDataSource.Creator = dataSource.Creator;
                pubDataSource.RTVersion = dataSource.RTVersion;
                pubDataSource.Type = dataSource.Type;
                pubDataSource.SolutionId = dataSource.SolutionId;
                pubDataSource.AuthenticationMode = dataSource.AuthenticationMode;
                pubDataSource.AuthenticationPassword = dataSource.AuthenticationPassword;
                pubDataSource.AuthenticationUser = dataSource.AuthenticationUser;
                pubDataSource.PublishedVersion = dataSource.Version;
                pubDataSource.PublishedTime = dataSource.PublishedTime;
                pubDataSourceRep.Create(pubDataSource);

                modelDataSource.DataSource = pubDataSource;

                List<Entities.EntDataSet> list = dataSetRep.GetList(p => p.DataSourceId == dataSourceId);
                for (int index = 0; index < list.Count; index++)
                {
                    Entities.EntPubDataSet pubDataSet = new Entities.EntPubDataSet();
                    pubDataSet.Id = Guid.NewGuid();
                    pubDataSet.DataSetId = list[index].Id;
                    pubDataSet.PubBatchId = pubDataSource.Id;
                    pubDataSet.Name = list[index].Name;
                    pubDataSet.Caption = list[index].Caption;
                    pubDataSet.Type = list[index].Type;
                    pubDataSet.ValueString = list[index].ValueString;
                    pubDataSet.DataSourceId = list[index].DataSourceId;
                    pubDataSet.CreatedTime = list[index].CreatedTime;
                    pubDataSet.Creator = list[index].Creator;

                    pubDataSetRep.Create(pubDataSet);

                    Models.PublishedDataSet modelDataSet = new Models.PublishedDataSet();
                    modelDataSet.DataSet = pubDataSet;

                    List<Entities.DataParameter> parameterList = dpRep.GetList(p => p.DataSetId == list[index].Id);
                    for (int pIndex = 0; pIndex < parameterList.Count; pIndex++)
                    {
                        Entities.EntPubDataParameter pubParameter = new Entities.EntPubDataParameter();
                        pubParameter.Id = Guid.NewGuid();
                        pubParameter.PubBatchId = pubDataSource.Id;
                        pubParameter.DataSetId = parameterList[pIndex].DataSetId;
                        pubParameter.Name = parameterList[pIndex].Name;
                        pubParameter.Caption = parameterList[pIndex].Caption;
                        pubParameter.ValueType = parameterList[pIndex].ValueType;
                        pubParameter.Type = parameterList[pIndex].Type;
                        pubParameter.DataSourceId = parameterList[pIndex].DataSourceId;
                        pubParameter.DataParameterId = parameterList[pIndex].Id;

                        pubDPRep.Create(pubParameter);

                        modelDataSet.DataParameters.Add(pubParameter);
                    }

                    modelDataSource.DataSets.Add(modelDataSet);
                }
                try
                {
                    if (dbContext.SaveChanges() > 0)
                    {
                        return new SingleResult<Models.PublishedDataSource>(true, 0, string.Empty, modelDataSource);
                    }
                }
                catch (Exception ex)
                {
                    CPPEI.Coolzon.Common.Logger.ErrorToTag(Library.LogTAG, string.Format("发布数据源:{0},ex:{1}", dataSourceId, ex));
                    return new SingleResult<Models.PublishedDataSource>(false, 1, string.Empty, null);
                }
            }

            return new SingleResult<Models.PublishedDataSource>(false, 1, string.Empty, null);
        }

        public ListResult<Models.PublishedDataSource> GetPublishedDataSourceList(Guid solutionId)
        {
            List<Models.PublishedDataSource> modelList = new List<Models.PublishedDataSource>();
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.EntPubDataSource> pubDataSourceRep = new Repositories.EntityRepository<Entities.EntPubDataSource>(dbContext);
                Repositories.EntityRepository<Entities.EntPubDataSet> pubDataSetRep = new Repositories.EntityRepository<Entities.EntPubDataSet>(dbContext);
                Repositories.EntityRepository<Entities.EntPubDataParameter> pubDPRep = new Repositories.EntityRepository<Entities.EntPubDataParameter>(dbContext);

                List<Entities.EntPubDataSource> pubDataSourceList = pubDataSourceRep.GetList();

                for (int index = 0; index < pubDataSourceList.Count; index++)
                {
                    Models.PublishedDataSource modelDataSource = new Models.PublishedDataSource();
                    modelDataSource.DataSource = pubDataSourceList[index];

                    modelList.Add(modelDataSource);

                    // 获取数据集
                    List<Entities.EntPubDataSet> pubDataSetList = pubDataSetRep.GetList(p => p.DataSourceId == pubDataSourceList[index].DataSourceId);
                    for (int indexPDSET = 0; indexPDSET < pubDataSetList.Count; indexPDSET++)
                    {
                        Models.PublishedDataSet modelDataSet = new Models.PublishedDataSet();
                        modelDataSet.DataSet = pubDataSetList[indexPDSET];
                        modelDataSource.DataSets.Add(modelDataSet);

                        // 获取参数
                        List<Entities.EntPubDataParameter> parameterList = pubDPRep.GetList(p => p.DataSourceId == modelDataSource.DataSource.DataSourceId && p.DataSetId == modelDataSet.DataSet.DataSetId);
                        for (int pIndex = 0; pIndex < parameterList.Count; pIndex++)
                        {
                            modelDataSet.DataParameters.Add(parameterList[pIndex]);
                        }
                    }

                }
                return new ListResult<Models.PublishedDataSource>(true, 0, string.Empty, modelList);
            }
        }
    }
}
